/**
 * Created by Administrator on 15-9-7.
 */
(function($){
	var errorTip = "验证失败";
	var Terminal = TerminalClass.extend({
		timer : null,
		INPUT_CHANGE_TIMEOUT : 20,
		LOADING_IMG : PFT_GLOBAL.CONFIG.LOADING_IMG,
		DEFAULT_IMG : PFT_GLOBAL.CONFIG.DEFAULT_IMG,
		xhr : null,
		//当产品数大于50个时，开启搜索功能(admin默认开启搜索)
		PRODUCT_COUNT_TRIGGER_SEARCH : 50,
		checkIsAdmin : function(){
			var isAdmin = $("#isAdmin").val();
			return isAdmin==1 ? true : false;
		},
		getTerminalTime : function(){
			return this.checkIsAdmin()==1 ? $("#termDateInp").val() : "";
		},
		init : function(){
			var self = this;
			var isAdmin = (this.checkIsAdmin() == 1) ? true : false;
			var termSearInp = $("#termSearInp");
			this.initProd();
			termSearInp.data("orignval",termSearInp.val());
			$("#termSearBtn").on("click",function(){
				var salerId = self.getSalerid();
				var voucher = $("#termSearInp").val();
				if(!voucher) return false;
				self.queryOrder(salerId,voucher);
				return false;
			})
			termSearInp.on("keyup",function(e){
				var keyCode = e.keyCode;
				if(keyCode==13){
					var salerId = self.getSalerid();
					var voucher = $("#termSearInp").val();
					if(!voucher) return false;
					self.queryOrder(salerId,voucher);
					return false;
				}
			}).on("click",function(e){
				var inp = $(this);
				var val = inp.val();
				var oval = inp.data("orignval");
				if(val==oval) inp.val("");
			}).on("blur",function(e){
				var inp = $(this);
				if(!inp.val()) inp.val(inp.data("orignval"));
			})
			//验证
			$("#myOrderList").on("click",".orderItem .checkBtn",function(e){
				var btn = $(e.currentTarget);
				var data = {};
				if(btn.hasClass("disabled") || btn.hasClass("success")) return false;
				btn.prev(".errorTip").remove();
				var endtimeInp = btn.parent().find(".termTimeInp");
				if(endtimeInp.length){ data["rtime"] = endtimeInp.val();}
				data["check"] = 1;
				data["salerid"] = self.getSalerid();
				data["ordernum"] = btn.attr("data-mainordernum") || "";
				data["list"] = {};
				btn.parents(".inCon").find(".ticketUl .ticketLi").each(function(){
					var item = $(this);
					var inp = item.find(".tinp");
					var ordernum = inp.attr("data-ordernum");
					var tnum = inp.val();
					data["list"][ordernum] = tnum;
				});
				var recheck = btn.attr("data-recheck");
				if(recheck=="1") data["recheck"] = 1;
				self.terminalCheck(btn,PFT_GLOBAL.U.JSON.stringify(data));
				return false;
			})
			//已取消订单 admin时 可验证但需先选择验证时间
			$("#myOrderList").on("click",".termTimeWrap",function(e){
				var p = $(e.currentTarget);
				var inp = p.find(".termTimeInp");
				var val = inp.val();
				inp.addClass("select");
				self.openCalendar(val);
			})
			//修改验证票数--focus
//			$("#myOrderList").on("click",".orderItem .tinp",function(e){
//				var inp = $(e.currentTarget);
//				var val = inp.val();
//				inp.data("lastval",val);
//				return false;
//			})
//			//修改验证票数--blur
//			$("#myOrderList").on("blur",".orderItem .tinp",function(e){
//				var inp = $(e.currentTarget);
//				var val = inp.val();
//				var ptype = inp.attr("data-ptype").toUpperCase();
//				var lastVal = inp.data("lastval");
//				var maxNum = inp.data("maxnum");
//				if(ptype=="F" || ptype=="C"){
//					var ptypename = ptype=="F" ? "套票产品" : "酒店产品";
//					if(val!=lastVal){
//						inp.val(lastVal);
//						alert(ptypename+"票数须全部验掉");
//						return false;
//					}
//				}
//				if(!PFT_GLOBAL.U.isPositiveNum(val)) inp.val(lastVal);
//				if(val>maxNum) inp.val(lastVal);
//			})
			this.on("calendarSelectDate",function(val){
				self.onCalendarSelectDate(val);
			})
			this.on("calendarClose",function(){
				self.onCalendarClose();
			})
		},
		initProd : function(){
			var self = this;
			var sid = $("#gsid").val() || "";
			//加载产品
			this.fetchProduct("",{
				loading : function(){
					$("#prodBoxStatus").show().html('<img class="loading" src="'+self.LOADING_IMG+'"/><span class="t">正在加载产品...</span>');
				},
				removeLoaidng : function(){},
				timeout : function(res){
					$("#prodBoxStatus").show().html('<span class="t">加载产品超时，请稍后重试...</span>');
				},
				serverError : function(res){
					$("#prodBoxStatus").show().html('<span class="t">加载产品出错，请稍后重试...</span>');
				},
				empty : function(res){
					$("#prodBoxStatus").show().html('<span class="t">没有产品...</span>');
				},
				success : function(res){
					var prodListUl = $("#prodListUl");
					$("#prodBoxStatus").hide();
					var maxProductCount = self.PRODUCT_COUNT_TRIGGER_SEARCH;
					var isAdmin = self.checkIsAdmin();
					var allHtml = self.buildProductUl(res.list);
					if(res.list.length>=maxProductCount || isAdmin) $("#prodSearchInp").attr("data-search",true);
					prodListUl.html(allHtml).on("click",".pItem",function(e){
						var item = $(e.currentTarget);
						self.onProdItemClick(item);
						return false;
					}).data("alldata",allHtml);
					prodListUl.children().first().trigger("click");
					$("#prodSearchInp").on("click",function(e){
						if($("#gsid").val()) return false;
						self.onSearchInpClick(e);
						return false;
					}).on("keyup",function(e){
						var keyCode = e.keyCode;
						self.onInputKeyup(keyCode);
						self.onProdInpupKeyup(e);
					});
					$(document).on("click",function(e){
						self.hideProdUl();
					})
				}
			},sid);
		},
		getCalendar : (function(){
			var c = null;
			return function(){
				if(!c) c = new CalendarCore();
				return c;
			}
		})(),
		openCalendar : function(val){
			var c = this.getCalendar();
			var container = $("#calendarContainer");
			var containerW = $("#calendarContainer").width();
			var winW = $(window).width();
			var inited = container.data("init");
			if(!inited){
				this.initCalendar();
				container.data("init","inited");
			}
			container.html(c.outputHtml(val)).show().css({
				"left" : (winW-containerW)/2
			})
			$("#mask").show().css({
				"background" : "#000",
				"opacity" : 0.5
			})
		},
		initCalendar : function(){
			var self = this;
			var c = this.getCalendar();
			var container = $("#calendarContainer");
			container.on("click",".closeCalendarBtn",function(e){
				$("#mask").hide();
				container.hide();
				self.fire("calendarClose");
			}).on("click",".valid",function(e){
				var target = $(e.currentTarget);
				var val = target.attr("data-date");
				val && self.fire("calendarSelectDate",val);
				$("#mask").hide();
				container.hide();
			}).on("click",".monthBtn",function(e){
				var btn = $(e.currentTarget);
				if(btn.hasClass("prevMonthBtn")){
					var prev = c.prevMonthOutput();
					container.html(prev);
				}else if(btn.hasClass("nextMonthBtn")){
					var next = c.nextMonthOutput();
					container.html(next);
				}
			})
		},
		onCalendarSelectDate : function(date){
			$("#myOrderList").find("input.select").val(date).removeClass("select");
		},
		onCalendarClose : function(){
			$("#myOrderList").find("input.select").removeClass("select");
		},
		getSalerid : function(){
			return $("#term_prodNum").text();
		},
		onSearchInpClick : function(e){
			this.showProdUl();
			//this.onProdInpupKeyup(e)
		},
		//产品选择input即时搜索 input change
		onProdInpupKeyup : function(e){
			var self = this;
			var inp = $(e.target);
			var val = inp.val();
			var listUl = $("#prodListUl");
			var keyCode = e.keyCode;
			var canSearch = inp.attr("data-search");
			if(keyCode==38 || keyCode==40 || keyCode==13 || !canSearch) return;
			if(!val){
				this.showProdUl();
				listUl.html(listUl.data("alldata"));
			}else{
				if(this.xhr && this.xhr.abort) this.xhr.abort();
				this.xhr = this.fetchProduct(val,{
					loading : function(){
						listUl.html('<li class="statusLi"><img class="loading" src="'+self.LOADING_IMG+'"/><span class="t">正在查找...</span></li>');
					},
					removeLoading : function(){ },
					timeout : function(){ listUl.html('<li class="statusLi"><span class="t">查询超时，请稍后重试...</span></li>');},
					serverError : function(){ listUl.html('<li class="statusLi"><span class="t">查询出错，请稍后重试...</span></li>');},
					empty : function(res){listUl.html('<li class="statusLi"><span class="t">没有相应产品...</span></li>');},
					success : function(res){
						var prodListUl = $("#prodListUl");
						var html = self.buildProductUl(res.list);
						prodListUl.show().html(html);
					}
				})
			}
		},
		//方向键 上&下  回车选择
		onInputKeyup : function(keyCode){
			var curItem = null, items,nextItem,prevItem,selectItem;
			if(keyCode==38){//上
				items = $("#prodListUl").children();
				curItem = $("#prodListUl").children(".select");
				if(!curItem.length) curItem = items.first();
				curItem.addClass("select");
				prevItem = curItem.prev();
				if(prevItem.length){
					prevItem.addClass("select");
					curItem.removeClass("select");
				}
			}else if(keyCode==40){
				items = $("#prodListUl").children();
				curItem = $("#prodListUl").children(".select");
				if(!curItem.length) curItem = items.first();
				curItem.addClass("select");
				nextItem = curItem.next();
				if(nextItem.length){
					nextItem.addClass("select");
					curItem.removeClass("select");
				}
			}else if(keyCode==13){
				selectItem = $("#prodListUl").children(".select");
				if(selectItem.length) this.onProdItemClick(selectItem);
			}
		},
		onProdItemClick : function(curOption){
			var id = curOption.attr("data-id");
			var terminal = curOption.attr("data-terminal");
			var salerid = curOption.attr("data-salerid");
			var src = curOption.attr("data-img");
			$("#prodSearchInp").val(curOption.text());
			$("#term_prodId").text(id);
			$("#term_termNum").text(terminal);
			$("#term_prodNum").text(salerid);
			this.loadPhotoImg(id,src);
			$("#prodListUl").children(".select").removeClass("select");
			curOption.addClass("select");
			this.hideProdUl();
		},
		showProdUl : function(){
			var listUl = $("#prodListUl");
			if(!listUl.data("offsetX") || !listUl.data("offsetY")){
				var inp = $("#prodSearchInp");
				var offset = inp.offset();
				var ox = offset.left;
				var oy = offset.top;
				oy = oy + inp.outerHeight(true);
				listUl.data("offsetX",ox);
				listUl.data("offsetY",oy);
				listUl.css({"top":oy,"left":ox});
			}
			$("#prodListUl").show();

		},
		hideProdUl : function(){ $("#prodListUl").hide();},
		//更换产品/景区  加载photo img
		loadPhotoImg : function(id,imgpath){
			if(!imgpath) return false;
			var container = $("#prodPhoto");
			var oimg = $("#photoImg"+id);
			var img = container.children(".loading");
			$(img).attr("src",imgpath);
			if(oimg.length){
				oimg.show().siblings().hide();
			}else{
				var img = new PFT_GLOBAL.U.ImgLoador({src:imgpath});
				img.on("loading",function(){
					container.children(".loading").show().siblings().hide();
				});
				img.on("loaded",function(img){
					container.children().hide();
					img = $(img);
					img.attr("id","photoImg"+id).attr("width",container.width()).attr("height",container.height()).show().appendTo(container);
				});
				img.on("error",function(){
					container.children(".error").show().siblings().hide();
				})
				img.load();
			}
		},
		onQueryOrderLoading : function(){
			var listUl = $("#myOrderList");
			listUl.html('<li class="status loading"><img class="icon" src="'+this.LOADING_IMG+'" alt=""/><span class="t">正在查询订单...</span></li>');
		},
		onQueryOrderRemoveLoading : function(){
			var listUl = $("#myOrderList");
			listUl.html("");
		},
		onQueryOrderTimeout : function(res){
			var listUl = $("#myOrderList");
			listUl.html('<li class="status timeout"><span class="t">查询订单超时,请稍后重试</span></li>');
		},
		onQueryOrderServerError : function(res){
			var listUl = $("#myOrderList");
			listUl.html('<li class="status timeout"><span class="t">服务器出错,请稍后重试</span></li>');
		},
		onQueryOrderSuccess : function(res){
			var listUl = $("#myOrderList");
			var html = '';
			for(var i in res){
				var d = res[i];
				var name = d["ordername"];
				var mobile = d["ordertel"];
				var num = d["ordernum"];
				var time = d["ordertime"];
				var begintime = d["begintime"];
				var tickets = d["tickets"];
				var status = d["status"];
				var checkBtnCls = d["checkBtnCls"];
				var checkBtnTxt = d["checkBtnTxt"];
				var payTypeTip = d["payTypeTip"];
				var endtime = d["endtime"];
				var ptype = d["ptype"];
				var ticketTxt = d["ticketTxt"];
				var flagHtml = "";
				var flag = d["flag"];
				var readonly = "readonly";
				for(var i in flag){
					flagHtml += '<span class="flag">'+flag[i]+'</span>';
				}
				html += '<li class="orderItem">';
				html += '<div class="oTit">联系人：<span class="contactor">'+name+'</span><span class="mobile">电话：'+mobile+'</span>'+flagHtml+'</div>';
				html += '<div class="itemCon">';
				html += '<div class="ltCon">';
				html += '<p class="line"><span class="lt"><span class="vhidden">订</span>订单号：</span><span class="rt">'+num+'</span></p>';
				html += '<p class="line"><span class="lt">下单时间：</span><span class="rt">'+time+'</span></p>';
				html += '<p class="line"><span class="lt">游玩时间：</span><span class="rt">'+begintime+'</span></p>';
				html += '</div>';
				html += '<div class="inCon">';
				html += '<ul class="ticketUl">';
				for(var s in tickets){
					var t = tickets[s];
					var tname = t["name"];
					var tnum = t["tnum"];
					var torder = t["ordernum"];
					html += '<li class="ticketLi clearfix">';
					html += '<div class="inpCtrol"><input class="tinp" type="text" value="'+tnum+'" '+readonly+' data-ptype="'+ptype+'" data-maxnum="'+tnum+'" data-mainordernum="'+num+'" data-ordernum="'+torder+'"/><span class="zhang">张</span></div>';
					html += '<div class="trnameCol"><p class="tname">【'+tname+'】</p><p class="bt">共<em class="tnum">'+tnum+'</em>张<i class="vt"></i>'+ticketTxt+'<em class="tnum">'+tnum+'</em>张</p></div>';
					html += '</li>';
				}
				html += '</ul>';
				html += '<div><a class="checkBtn '+checkBtnCls+'" href="###" data-mainordernum="'+num+'">'+checkBtnTxt+'</a>'+payTypeTip;
				if(endtime){
					html += '<span class="termTimeWrap"><input class="termTimeInp" type="text" value="'+endtime+'"/><i class="iconfont">&#xe65b;</i></span>';
				}
				html += '';
				html += '</div>';
				html += '<p class=""></p>';
				html += '</div></div></li>';
			}
			listUl.html(html);
		},
		onQueryOrderEmpty : function(res){
			var listUl = $("#myOrderList");
			listUl.html('<li class="status empty"><span class="t">查无订单...</span></li>');
		},
		onQueryOrderLoginOut : function(){
			alert("登录过期，请重新登录");
			window.location.href="dlogin_n.html";
		},
		onCheckLoading : function(btn,data){
			btn.text("正在验证...");
		},
		onCheckRemoveLoading : function(btn,data){
			btn.text("验 证");
		},
		onCheckTimeout : function(btn,data,res){
			var errorTip = res.msg || errorTip;
			btn.text("重新验证").before('<span class="errorTip"><i class="iconfont">&#xe654;</i>验证超时</span>');
		},
		onCheckServerError : function(btn,data,res){
			btn.text("重新验证").before('<span class="errorTip"><i class="iconfont">&#xe654;</i>服务器出错</span>');
		},
		onCheckLoginOut : function(res){
			alert("登录已过期，请重新登录");
			window.location.href="dlogin_n.html";
		},
		onCheckFail : function(btn,data,res){
			var errorTip = res.msg || "验证失败";
			btn.text("重新验证").attr("data-recheck",1).before('<span class="errorTip"><i class="iconfont">&#xe654;</i> '+errorTip+'</span>');
		},
		onCheckSuccess : function(btn,data,res){
			btn.addClass("success").removeAttr("data-recheck").html('<i class="iconfont">&#xe63f;</i><span class="t">验证成功</span>').css("padding","0 31px");
			btn.parent().children(".ticketUl").find(".tinp").attr("readonly","readonly");
		},
		buildProductUl : function(data){
			var html = "";
			for(var i in data){
				var d = data[i];
				var id = d["id"];
				var salerid = d["salerid"];
				var terminal = d["terminal"];
				var imgpath = d["imgpath"];
				var title = d["title"] || "无标题产品";
				html += '<li class="pItem" data-id="'+id+'" data-salerid="'+salerid+'" data-terminal="'+terminal+'" data-img="'+imgpath+'">'+title+'</li>';
			}
			return html;
		}
	});

	window.Terminal = Terminal;

})(jQuery);
